package cn.itsource.user.service.impl;

import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.dto.UserDto;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();

        //1.校验
        //1.1.空值校验
        if(StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("请输入正确的数据!!!");
        }
        //1.2.两次密码是否相同
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致!!!");
        }
        //1.3.验证码是否过期
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj == null){
            throw new BusinessException("验证码无效，请重新获取!!!");
        }
        //1.4.验证码是否正确  //  9527:1223555555
        String codeTmp = obj.toString().split(":")[0];
        if(!codeTmp.equalsIgnoreCase(phoneCode)){
            throw new BusinessException("验证码错误!!!");
        }

        //2.保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.add(logininfo);//自增
        //2.2.再保存t_user
        user.setLogininfoId(logininfo.getId());
        //user.setLogininfo(logininfo);
        userMapper.add(user);
        System.out.println("--------------------操作成功------------------------");
    }

    @Override
    public void emailRegister(UserDto userDto) {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();

        //1.校验
        //1.1.空值校验
        if(StringUtils.isEmpty(email)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("请输入正确的数据!!!");
        }
        //1.2.两次密码是否相同
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致!!!");
        }

        //1.3.判断邮箱是否已被注册
        User userByEmail = userMapper.findByEmail(userDto.getEmail());
        if(userByEmail!=null){
            throw new BusinessException("该邮箱已经被注册，请直接登录");
        }

        //2.保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.add(logininfo);//自增
        //2.2.再保存t_user
        user.setLogininfoId(logininfo.getId());
        //user.setLogininfo(logininfo);
//        System.out.println(user);
        userMapper.add(user);
        System.out.println("--------------------操作成功------------------------");
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Password = Md5Utils.encrypByMd5(userDto.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        user.setEmail(userDto.getEmail());
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo);
        //当前对象是用户
        logininfo.setType(1);
        return logininfo;
    }

    @Override
    public void add(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Password = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Password);

        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        super.add(user);
    }

    @Override
    public void delete(Long id) {
        //获取登录信息id
        Long logininfo_id = userMapper.findById(id).getLogininfoId();
        //删除登录信息对象
        logininfoMapper.delete(id);
        //删除用户信息
        super.delete(id);
    }

    @Override
    public void update(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Password = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        //用户user：createtime和logininfo_id不能修改

        //获取登录信息id
        Long logininfo_id = userMapper.findById(user.getId()).getLogininfoId();
        //登录信息logininfo：type不修改
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);
        super.update(user);
    }
}
